package com.zzzzzz.sys.city;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.util.WebUtils;
import com.google.common.collect.Lists;
import com.zzzzzz.core.datagrid.BaseData;
import com.zzzzzz.core.datagrid.BaseQueryForm;
import com.zzzzzz.oms.GCS;
import com.zzzzzz.plugins.poi.ExportExcel;
import com.zzzzzz.plugins.poi.ImportExcel;
import com.zzzzzz.plugins.shiro.ShiroUtils;
import com.zzzzzz.utils.page.Page;

/**
 * @author hing
 * @version 1.0.0
 */
@Controller
public class CityWeb {

	@Resource
	public CityService cityService;
	
	@Resource
	public CityDao cityDao;

	@RequestMapping(value = "/city/list", method = RequestMethod.GET)
	public String list() {
		return "sys/city";
	}

	// 增加、修改
	@RequestMapping(value = "/city/save", method = RequestMethod.POST)
	@ResponseBody
	public BaseData save(@RequestBody @Valid City city, BindingResult bindingResult) throws Exception {
		if (bindingResult.hasErrors()) {
			return new BaseData(GCS.ERRCD_PARAM);
		}
		cityService.save(city, ShiroUtils.findUser());
		return new BaseData("0");
	}
	
	// 停用数据
	@RequestMapping(value = "/city/updStByIds", method = RequestMethod.POST)
	@ResponseBody
	public BaseData updStByIds(@RequestParam(value = "ids", required = true) List<Long> ids, @RequestParam(value = "st", required = true) Integer st) throws Exception {
		cityDao.updStByIds(ids, st, ShiroUtils.findUser());
		return new BaseData("0");
	}	  
	
	// 查找一条数据
	@RequestMapping(value = "/city/id/{id}", method = RequestMethod.GET)
	@ResponseBody 
	public BaseData findById(@PathVariable Long id) {
		City city = cityDao.findById(id);
		return new BaseData(city, null);
	}
	
	// 动态查询
	@RequestMapping(value = "/city/findListBy", method = RequestMethod.POST)
	@ResponseBody
	public BaseData findListBy(@RequestBody BaseQueryForm baseQueryForm) {
		List<City> list; 
		Page page;
		BaseData baseData;
		if(baseQueryForm.getPageNb()==null&&baseQueryForm.getPageSize()==null){
			list = cityDao.findListBy(null,baseQueryForm.getFfMap());
			baseData=new BaseData(list,null);
		}else{
			page=baseQueryForm.getPage();
			list = cityDao.findListBy(page,baseQueryForm.getFfMap());
			baseData=new BaseData(list, page.getTotal());
		}
		return baseData;
	}
	
	//按照字母排序
	@RequestMapping(value = "/city/findListByFirst", method = RequestMethod.POST)
	@ResponseBody
	public BaseData findListByFirst() {
		List<City> list = cityDao.findListByFirst(ShiroUtils.findUser());
		BaseData baseData=new BaseData(list, null);
		return baseData;
	}
	
	// 导入
	@RequestMapping(value = "/city/import", method=RequestMethod.POST)
    public String importExcel(@RequestParam MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			if(StringUtils.isBlank(file.getOriginalFilename())){
				List<BaseData> list3=new ArrayList<BaseData>();
				BaseData baseData=new BaseData();
				baseData.setErrMsg("您还没选择文件，请先选择需要导入的文件！");
				list3.add(baseData);
				redirectAttributes.addFlashAttribute("msg",list3);
			}else{
				ImportExcel importExcel = new ImportExcel(file, 1, 0);
				if(file.getOriginalFilename().contains("城市")){
					List<City> list = importExcel.getDataList(City.class);
					List<BaseData> list1 =cityService.batchAdd(list, ShiroUtils.findUser());
					redirectAttributes.addFlashAttribute("msg", list1);
				}else{
					List<BaseData> list2=new ArrayList<BaseData>();
					BaseData baseData=new BaseData();
					baseData.setErrMsg("你导入模板有误，请重新选择模板导入。");
					list2.add(baseData);
					redirectAttributes.addFlashAttribute("msg",list2);
				}
			}			
		} catch (Exception e) {
			redirectAttributes.addFlashAttribute("msg", "导入数据保存失败。");
			logger.warn("importExcel", e);
		}
		return "redirect:/msg";
    }
	
	//下载导入模板
	@RequestMapping(value = "city/import/template")
	public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
	        	String fileName = "城市数据导入模板.xlsx";
	    		List<City> list = Lists.newArrayList();
	    		new ExportExcel("城市数据导入模板", City.class, 2).setDataList(list).write(response, fileName).dispose();
	    		return null;
			} catch (Exception e) {
			redirectAttributes.addFlashAttribute("msg", "城市数据导入模板下载失败。");
			logger.warn("importFileTemplate", e);
		}
			return "redirect:/msg";
	 }
	  
	// 导出
	 @RequestMapping(value = "/city/export")
	 public String exportFileTemplate(HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {				
			Map<String, Object> params = WebUtils.getParametersStartingWith(request, null);
	        String fileName = "城市数据.xlsx"; 
	        List<City> list = cityDao.findListBy(null, params);
	    	new ExportExcel("城市数据", City.class, 1).setDataList(list).write(response, fileName).dispose();
	    	return null;
			} catch (Exception e) {
				redirectAttributes.addFlashAttribute("msg", "城市数据导出失败。");
				logger.warn("importFileTemplate", e);
			}
			return "redirect:/msg";
	 }
	private static final Logger logger = LoggerFactory.getLogger(CityWeb.class);
}
